package com.ctsi.commons.event;

import com.ctsi.commons.event.config.Event;
import com.ctsi.commons.util.UtilValidate;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

class EventList {

	private final List<Event> singeTonList = new CopyOnWriteArrayList<Event>();

	public List<Event> getSingeTonList() {
		return singeTonList;
	}

	private List<Event> prototypeList;

	public List<Event> getPrototypeList() {
		return prototypeList;
	}

	public List<Event> getEvent() {
		if (UtilValidate.isEmpty(prototypeList)) {
			return singeTonList;
		} else {
			List<Event> result = new ArrayList<Event>(prototypeList.size() + 4);
			result.addAll(prototypeList);
			if (UtilValidate.isNotEmpty(singeTonList)) {
				result.addAll(singeTonList);
			}
			return result;
		}
	}

	public boolean contains(Event o) {

		if (singeTonList.contains(o)) {
			return true;
		}

		if (prototypeList != null) {
			if (prototypeList.contains(o)) {
				return true;
			}
		}
		return false;
	}

	public void add(Event e) {
		if (e.isSingleton()) {
			singeTonList.add(e);
		} else {
			if (prototypeList == null) {
				synchronized (this) {
					if (prototypeList == null) {
						prototypeList = new CopyOnWriteArrayList<Event>();
					}

				}

			}
			prototypeList.add(e);
		}
	}

	public boolean isEmpty() {
		return UtilValidate.isEmpty(singeTonList) && UtilValidate.isEmpty(prototypeList);
	}
}
